<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div>
      ws地址<input style="width: 300px" type="text" name="" id="ws" />
      <button onclick="connect()">链接</button>
      <button onclick="disconnect()">断开</button>
    </div>
    <div>
      昵称<input type="text" id="uname" />
      <button onclick="modify()">修改</button>
    </div>
    <div style="display: flex">
      <div>
        <textarea name="" id="send" cols="30" rows="50"></textarea>
        <button onclick="sendMessage()">send</button>
      </div>
      <div>
        <textarea name="" id="receive" cols="30" rows="50"></textarea>
      </div>
    </div>
    <script>
      var connection = null;
      ws.value = `ws://127.0.0.1:3000/ws-chat`;
      send.value = `{
          "from": "匿名",
          "type": "chat-message",
          "data": {
              "type": "text",
              "data": "你好呀，我是匿名"
          }
      }
            `;
      function sendMessage() {
        if (!connection) {
          return alert("先链接");
        }
        connection.send(send.value);
      }

      function modify() {
        if (!connection) {
          return alert("先链接");
        }
        connection.send(`{
    "from": "匿名",
    "type": "modify-uinfo",
    "data": {
        "name": "${uname.value}"
    }
}`);
      }
      function connect() {
        if (connection) {
          return alert("已经链接");
        }
        connection = new WebSocket(ws.value);
        console.log(connection);
        connection.onmessage = function (message) {
          receive.value = message.data;
        };
      }
      function disconnect() {
        if (!connection) {
          return alert("先链接");
        }
        connection.close();
        connection = null;
      }
    </script>
  </body>
</html>
